// 卡牌游戏主要JavaScript文件

// API基础URL
const API_BASE_URL = '/api';

// 通用AJAX请求函数
function apiRequest(url, method = 'GET', data = null, headers = {}) {
    const options = {
        method: method,
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken'),
            ...headers
        }
    };
    
    if (data) {
        options.body = JSON.stringify(data);
    }
    
    return fetch(API_BASE_URL + url, options)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        });
}

// 获取CSRF Token
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

// 显示消息提示
function showMessage(message, type = 'info') {
    const alertClass = {
        'success': 'alert-success',
        'error': 'alert-danger',
        'warning': 'alert-warning',
        'info': 'alert-info'
    }[type] || 'alert-info';
    
    const alertHtml = `
        <div class="alert ${alertClass} alert-dismissible fade show" role="alert">
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;
    
    // 在页面顶部显示消息
    const container = document.querySelector('.container');
    if (container) {
        container.insertAdjacentHTML('afterbegin', alertHtml);
    }
}

// 加载状态管理
function setLoading(element, loading = true) {
    if (loading) {
        element.disabled = true;
        element.innerHTML = '<span class="loading-spinner"></span> 加载中...';
    } else {
        element.disabled = false;
        element.innerHTML = element.dataset.originalText || '提交';
    }
}

// 卡牌相关功能
class CardManager {
    static async buyCard(cardId, quantity = 1) {
        try {
            const response = await apiRequest('/cards/buy/', 'POST', {
                card_id: cardId,
                quantity: quantity
            });
            
            showMessage('购买成功！', 'success');
            return response;
        } catch (error) {
            showMessage('购买失败：' + error.message, 'error');
            throw error;
        }
    }
    
    static async getUserCards() {
        try {
            return await apiRequest('/cards/owned/');
        } catch (error) {
            showMessage('获取卡牌失败：' + error.message, 'error');
            throw error;
        }
    }
}

// 卡组相关功能
class DeckManager {
    static async createDeck(name) {
        try {
            const response = await apiRequest('/decks/', 'POST', { name: name });
            showMessage('卡组创建成功！', 'success');
            return response;
        } catch (error) {
            showMessage('创建卡组失败：' + error.message, 'error');
            throw error;
        }
    }
    
    static async addCardToDeck(deckId, cardId, quantity = 1) {
        try {
            const response = await apiRequest(`/decks/${deckId}/cards/`, 'POST', {
                card_id: cardId,
                quantity: quantity
            });
            showMessage('卡牌添加成功！', 'success');
            return response;
        } catch (error) {
            showMessage('添加卡牌失败：' + error.message, 'error');
            throw error;
        }
    }
    
    static async removeCardFromDeck(deckId, cardId) {
        try {
            const response = await apiRequest(`/decks/${deckId}/cards/${cardId}/`, 'DELETE');
            showMessage('卡牌移除成功！', 'success');
            return response;
        } catch (error) {
            showMessage('移除卡牌失败：' + error.message, 'error');
            throw error;
        }
    }
}

// 游戏相关功能
class GameManager {
    static async playCard(gameId, cardId) {
        try {
            const response = await apiRequest(`/games/${gameId}/play-card/`, 'POST', {
                card_id: cardId
            });
            showMessage('出牌成功！', 'success');
            return response;
        } catch (error) {
            showMessage('出牌失败：' + error.message, 'error');
            throw error;
        }
    }
    
    static async getGameStatus(gameId) {
        try {
            return await apiRequest(`/games/${gameId}/status/`);
        } catch (error) {
            showMessage('获取游戏状态失败：' + error.message, 'error');
            throw error;
        }
    }
    
    static async joinGame(gameId, deckId) {
        try {
            const response = await apiRequest(`/games/${gameId}/join/`, 'POST', {
                deck_id: deckId
            });
            showMessage('成功加入游戏！', 'success');
            return response;
        } catch (error) {
            showMessage('加入游戏失败：' + error.message, 'error');
            throw error;
        }
    }
}

// 匹配相关功能
class MatchmakingManager {
    static async joinMatchmaking(deckId) {
        try {
            const response = await apiRequest('/matchmaking/join/', 'POST', {
                deck_id: deckId
            });
            
            if (response.game_id) {
                showMessage('匹配成功！游戏ID：' + response.game_id, 'success');
                // 跳转到游戏页面
                window.location.href = `/games/${response.game_id}/`;
            } else {
                showMessage('已加入匹配队列，等待其他玩家...', 'info');
            }
            
            return response;
        } catch (error) {
            showMessage('加入匹配失败：' + error.message, 'error');
            throw error;
        }
    }
    
    static async leaveMatchmaking() {
        try {
            const response = await apiRequest('/matchmaking/leave/', 'POST');
            showMessage('已离开匹配队列', 'info');
            return response;
        } catch (error) {
            showMessage('离开匹配失败：' + error.message, 'error');
            throw error;
        }
    }
    
    static async getMatchmakingStatus() {
        try {
            return await apiRequest('/matchmaking/status/');
        } catch (error) {
            showMessage('获取匹配状态失败：' + error.message, 'error');
            throw error;
        }
    }
}

// WebSocket连接管理
class WebSocketManager {
    constructor(gameId) {
        this.gameId = gameId;
        this.socket = null;
        this.reconnectAttempts = 0;
        this.maxReconnectAttempts = 5;
    }
    
    connect() {
        const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
        const wsUrl = `${protocol}//${window.location.host}/ws/game/${this.gameId}/`;
        
        this.socket = new WebSocket(wsUrl);
        
        this.socket.onopen = () => {
            console.log('WebSocket连接已建立');
            this.reconnectAttempts = 0;
        };
        
        this.socket.onmessage = (event) => {
            const data = JSON.parse(event.data);
            this.handleMessage(data);
        };
        
        this.socket.onclose = () => {
            console.log('WebSocket连接已关闭');
            this.attemptReconnect();
        };
        
        this.socket.onerror = (error) => {
            console.error('WebSocket错误:', error);
        };
    }
    
    handleMessage(data) {
        switch (data.type) {
            case 'game_update':
                this.onGameUpdate(data.data);
                break;
            case 'game_status':
                this.onGameStatus(data.data);
                break;
            case 'error':
                showMessage('游戏错误：' + data.message, 'error');
                break;
        }
    }
    
    onGameUpdate(gameData) {
        // 更新游戏界面
        console.log('游戏更新:', gameData);
        // 这里可以根据游戏数据更新界面
    }
    
    onGameStatus(gameStatus) {
        // 更新游戏状态
        console.log('游戏状态:', gameStatus);
        // 这里可以根据游戏状态更新界面
    }
    
    attemptReconnect() {
        if (this.reconnectAttempts < this.maxReconnectAttempts) {
            this.reconnectAttempts++;
            console.log(`尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
            setTimeout(() => {
                this.connect();
            }, 2000 * this.reconnectAttempts);
        } else {
            showMessage('连接失败，请刷新页面重试', 'error');
        }
    }
    
    disconnect() {
        if (this.socket) {
            this.socket.close();
        }
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 初始化工具提示
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
    
    // 初始化弹出框
    const popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'));
    popoverTriggerList.map(function (popoverTriggerEl) {
        return new bootstrap.Popover(popoverTriggerEl);
    });
});
